<?php

namespace app\api\controller;

use Throwable;
use ba\Captcha;
use ba\ClickCaptcha;
use think\facade\Config;
use app\common\facade\Token;
use thinkct\controller\Frontend;
use app\api\validate\User as UserValidate;

class User extends Frontend
{
    protected array $noNeedLogin = ['checkIn', 'logout', 'login', 'register', 'mobile_login'];

    protected array $noNeedPermission = ['index'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 会员签入(登录和注册)
     * @throws Throwable
     */
    public function checkIn(): void
    {
        $openMemberCenter = Config::get('buildadmin.open_member_center');
        if (!$openMemberCenter) {
            $this->error(__('Member center disabled'));
        }

        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(__('You have already logged in. There is no need to log in again~'), [
                'type' => $this->auth::LOGGED_IN
            ], $this->auth::LOGIN_RESPONSE_CODE);
        }

        if ($this->request->isPost()) {
            $params = $this->request->post(['tab', 'email', 'mobile', 'username', 'password', 'keep', 'captcha', 'captchaId', 'captchaInfo', 'registerType']);
            if (!in_array($params['tab'], ['login', 'register'])) {
                $this->error(__('Unknown operation'));
            }

            $validate = new UserValidate();
            try {
                $validate->scene($params['tab'])->check($params);
            } catch (Throwable $e) {
                $this->error($e->getMessage());
            }

            if ($params['tab'] == 'login') {
                $captchaObj = new ClickCaptcha();
                if (!$captchaObj->check($params['captchaId'], $params['captchaInfo'])) {
                    $this->error(__('Captcha error'));
                }
                $res = $this->auth->login($params['username'], $params['password'], (bool)$params['keep']);
            } elseif ($params['tab'] == 'register') {
                $captchaObj = new Captcha();
                if (!$captchaObj->check($params['captcha'], ($params['registerType'] == 'email' ? $params['email'] : $params['mobile']) . 'user_register')) {
                    $this->error(__('Please enter the correct verification code'));
                }
                $res = $this->auth->register($params['username'], $params['password'], $params['mobile'], $params['email']);
            }

            if (isset($res) && $res === true) {
                $this->success(__('Login succeeded!'), [
                    'userInfo'  => $this->auth->getUserInfo(),
                    'routePath' => '/user'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: __('Check in failed, please try again or contact the website administrator~');
                $this->error($msg);
            }
        }

        $this->success('', [
            'accountVerificationType' => get_account_verification_type()
        ]);
    }

    public function logout(): void
    {
        if ($this->request->isPost()) {
            $refreshToken = $this->request->post('refreshToken', '');
            if ($refreshToken) Token::delete((string)$refreshToken);
            $this->auth->logout();
            $this->success();
        }
    }
    /**
     * 登录账号
     */
    public function login(): void
    {
//        return $this->request->post(['username']);

        $openMemberCenter = Config::get('buildadmin.open_member_center');
        if (!$openMemberCenter) {
            $this->error(__('Member center disabled'));
        }

        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(__('You have already logged in. There is no need to log in again~'), [
                'routePath' => '/user'
            ], 302);
        }

        if ($this->request->isPost()) {
            $params = $this->request->post(['username', 'password', 'keep', 'captcha', 'captchaId', 'captchaInfo']);
//            $validate = new UserValidate();
//            try {
//                $validate->scene('login')->check($params);
//            } catch (Throwable $e) {
//                $this->error($e->getMessage());
//            }

//            $captchaObj = new ClickCaptcha();
//            if (!$captchaObj->check($params['captchaId'], $params['captchaInfo'])) {
//                $this->error(__('Captcha error'));
//            }

            $res = $this->auth->login($params['username'], $params['password'], (bool)$params['keep']);
            if ($res === true) {
                $this->success(__('Login succeeded!'), [
                    'userInfo'  => $this->auth->getUserInfo(),
                    'routePath' => '/user'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: __('Login failed, please try again or contact the website administrator~');
                $this->error($msg);
            }
        }
    }

    /**
     * 手机验证码登录
     */
    public function mobile_login(): void
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile) {
            $this->error('请输入手机号');
        }
        if (!$captcha) {
            $this->error('请输入验证码');
        }

        $captchaObj = new Captcha();
        if (!$captchaObj->check($captcha, $mobile . 'user_login')) {
            $this->error(__('Please enter the correct verification code'));
        }
        $user = \app\common\model\User::where('mobile', $mobile)->find();
        if (!$user) {
            $this->error('手机号未注册');
        }
        $this->auth->direct($user->id);
        $this->success(__('Login succeeded!'), [
            'userInfo'  => $this->auth->getUserInfo(),
            'routePath' => '/user'
        ]);
    }

    /**
     * 注册账号
     */
    public function register(): void
    {
        $openMemberCenter = Config::get('buildadmin.open_member_center');
        if (!$openMemberCenter) {
            $this->error(__('Member center disabled'));
        }

        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(__('You have already logged in. There is no need to log in again~'), [
                'routePath' => '/user'
            ], 302);
        }

        // 检测是否开启注册
        if(!get_sys_config('user_register')) {
            $this->error('未开启注册功能');
        }

        // 判断是否注册验证
        if(get_sys_config('user_register_verify')) {
            $captcha = $this->request->post('captcha');
            $registerType = $this->request->post('registerType');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile');
            if (!$captcha) {
                $this->error('请输入验证码');
            }
            $captchaObj = new Captcha();
            // 66983239@qq.comuser_register
            //die(($registerType == 'email' ? $email : $mobile) . 'user_register');
            if (!$captchaObj->check($captcha, ($registerType == 'email' ? $email : $mobile) . 'user_register')) {
                $this->error(__('Please enter the correct verification code'));
            }
        }
        //die('dd22');

        if ($this->request->isPost()) {

            $params = $this->request->post(['username', 'password', 'mobile', 'email', 'captcha', 'registerType']);
//            $validate = new UserValidate();
//            try {
//                $validate->scene('register')->check($params);
//            } catch (Throwable $e) {
//                $this->error($e->getMessage());
//            }

//            $captchaObj = new Captcha();
//            if (!$captchaObj->check($params['captcha'], ($params['registerType'] == 'email' ? $params['email'] : $params['mobile']) . 'user_register')) {
//                $this->error(__('Please enter the correct verification code'));
//            }

            $res = $this->auth->register($params['username'], $params['password'], $params['mobile'], $params['email']);
            if ($res === true) {
                // 注册成功增加默认角色
                if (1 === 1) {
                    $app = \app\admin\model\ai\app\Models::where('is_default', 1)->select()->toArray();
                    // 遍历数据
                    foreach ($app as $value) {
                        // 创建聊天组
                        \thinkct\facade\ChatData::createGroup($value['name'], $this->auth->id, $value['id']);
                    }
                }

                // 注册赠送余额
                $user_new = \app\common\model\User::where('id', $this->auth->id)->find();
                if (get_sys_config('user_register_money') > 0) {
                    $user_new->money = get_sys_config('user_register_money');
                    $user_new->save();
                    \app\common\model\UserMoneyLog::create([
                        'user_id' => $user_new->id,
                        'money' => get_sys_config('user_register_money'),
                        'before' => $user_new->money - get_sys_config('user_register_money'),
                        'after' => $user_new->money,
                        'memo' => '注册赠送余额' . get_sys_config('user_register_money') . '元',
                    ]);
                }
                // 注册赠送积分
                if (get_sys_config('user_register_score') > 0) {
                    $user_new->score = get_sys_config('user_register_score');
                    $user_new->save();
                }



                $this->success(__('Registration succeeded!'), [
                    'userInfo'  => $this->auth->getUserInfo(),
                    'routePath' => '/user'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: __('Registration failed, please try again or contact the website administrator~');
                $this->error($msg);
            }
        }
    }
}